package com.chat.api.web.restctrl;

import com.alibaba.fastjson.JSONObject;
import com.chat.api.common.exception.ApiException;
import com.chat.api.exception.CoreExceptionEnum;
import com.chat.api.utils.ResultUtil;
import com.chat.api.utils.SysUtils;
import com.chat.api.utils.util.DateUtil;
import com.chat.api.utils.util.IdWorkerUtil;
import com.chat.api.utils.util.ParamUtil;
import com.chat.api.web.po.BlogBean;
import com.chat.api.web.po.UserBean;
import com.chat.api.web.service.ActivityService;
import com.chat.api.web.service.BlogService;
import com.chat.api.web.service.UserService;
import com.chat.api.web.vo.BlogEntity;
import com.chat.api.web.vo.MessageEntity;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/blog")
public class BlogCtrl {

    @Autowired
    private BlogService blogService;
    @Autowired
    private UserService userService;
    @Autowired
    private ActivityService activityService;

    @RequestMapping("list")
    @ApiOperation("跳转博客主页")
    public String list(ModelMap model, HttpServletRequest request) {
        String idStr = ParamUtil.getParameter(request, "id", "");
        HttpSession session = request.getSession();
        String user = (String) session.getAttribute(session.getId());
        Long id = ParamUtil.getLongParameter(user, -1L);
        model = blogService.getList(id,model);
        return "/blog/blog";
    }

    @RequestMapping(value = "issue",produces = "application/json",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("保存并提交博客")
    public MessageEntity issue(@RequestParam(value = "content") String content,
                               @RequestParam(value = "title") String title,HttpServletRequest request) {
        BlogEntity entity = new BlogEntity();
        entity.setContent(content);
        entity.setTitle(title);
        entity.setCreateDate(DateUtil.getNowDate(12));
        if (StringUtils.isBlank(title)){
            return ResultUtil.fail("标题不能为空");
        }
        MessageEntity result = blogService.issue(entity, request);
        return result;
    }

    @RequestMapping(value = "getDetail",method = RequestMethod.GET)
    @ApiOperation("获取博客详情")
    public String getDetail(ModelMap model, HttpServletRequest request, @RequestParam(value = "id") String idStr) {
        if (StringUtils.isBlank(idStr)){
            return "id不能为空";
        }
        Long id = ParamUtil.getLongParameter(idStr, -1L);
        model = blogService.getDetail(id,model);
        return "/blog/blog.detail";
    }

    @RequestMapping("moreBlog")
    @ResponseBody
    @ApiOperation("加载更多博客")
    public MessageEntity getMoreBlog(@RequestParam(value = "pageNum") String pageNumStr, HttpServletRequest request) {
        if (StringUtils.isBlank(pageNumStr)){
            throw new ApiException("加载更多博客，pageNum不能为空");
        }
        Integer pageNum = Integer.parseInt(pageNumStr);
        List<BlogEntity> list = blogService.getMoreList(pageNum);
        return ResultUtil.success(list);
    }

    @RequestMapping(value = "approveBlog",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("博客审核")
    public MessageEntity approveBlog(@RequestParam(value = "id") String ids,
                                     @RequestParam(value = "result") Integer result,HttpServletRequest request) {
//        String ids = ParamUtil.getAttribute(request, "id");
//        Integer result = ParamUtil.getIntParameter(request, "result");
        // TODO 博客发布审批
        UserBean userBean = userService.findByUserInfo(request);
        if (!userBean.getUsername().equals("zhanzhu")){
            return ResultUtil.fail("该用户没有权限");
        }
        return blogService.approvalBlog(ids,result);
    }

    @RequestMapping("approvalBlogList")
    @ResponseBody
    @ApiOperation("获取待审批博客列表")
    public MessageEntity approvalBlogList(HttpServletRequest request) {
        UserBean userInfo = userService.findByUserInfo(request);
//        if (!userInfo.getUsername().equals("liutao")){
//            return ResultUtil.success("该用户没有权限！！！");
//        }
        String type = ParamUtil.getParameter(request, "type");
        return blogService.getApprovalList(type,userInfo);
    }

    @RequestMapping(value = "editBlog",method = RequestMethod.GET)
    @ApiOperation("编辑博客")
    public String editBlog(ModelMap model,@RequestParam(value = "id") String ids, HttpServletRequest request) {
        BlogBean blogBean = blogService.editBlog(ids);
        BlogEntity entity = new BlogEntity();
        entity.setValue(blogBean);
        model.addAttribute("blog",entity);
        return "/blog/edit";
    }

    @RequestMapping(value = "delBlog",method = RequestMethod.POST)
    @ApiOperation("删除博客")
    public String delBlog(ModelMap model,@RequestParam(value = "id") String ids, HttpServletRequest request) {
        Boolean result = blogService.delBlog(ids);
        return "/blog/myBlog";
    }

    @RequestMapping(value = "getApprovalRate",method = RequestMethod.GET)
    @ApiOperation("获取博客审批进度")
    public void getApprovalRate(HttpServletRequest request,@RequestParam(value = "id") String ids, HttpServletResponse response) {
        blogService.getApprovalRate(ids,response);
    }

    @RequestMapping(value = "deployActi",method = RequestMethod.GET)
    @ApiOperation("部署审批流程")
    public MessageEntity deployActi(HttpServletRequest request, HttpServletResponse response) {
        UserBean user = userService.findByUserInfo(request);
        if (!user.getUsername().equals("zhanzhu")){
            return ResultUtil.fail("该用户没有权限！！！");
        }
        activityService.deployActivity(request,user);
        return ResultUtil.success("部署完成！");
    }

    @RequestMapping(value = "test",method = RequestMethod.GET)
    @ApiOperation("test")
    public MessageEntity test(HttpServletRequest request, HttpServletResponse response) {
        return activityService.test();
    }

    @ResponseBody
    @RequestMapping(value = "/upload",produces = "application/json",method = RequestMethod.POST)
    public void upLoad(@RequestParam(value = "editormd-image-file", required = false) MultipartFile file,
                             HttpServletRequest request,HttpServletResponse response) {
        String ipAddr = SysUtils.getIpAddr(request);
        System.out.println("---------------------图片上传ip：" + ipAddr + "   时间：" + DateUtil.dateToStr(new Date(),8));
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter wirte = null;
        JSONObject json = new JSONObject();
        try {
            wirte = response.getWriter();
            //文件存放的路径
            //得到工程的路径：
            System.out.println("得到工程的路径："+System.getProperty("user.dir"));//user.dir指定了当前的路径
            //得到工程目录：
            System.out.println( "得到工程目录："+request.getSession().getServletContext().getRealPath("")); //参数可具体到包名
            //得到IE地址栏地址  request.getRequestURL()
            System.out.println( "得到IE地址栏地址  :"+ request.getRequestURL());
            // 得到相对地址：request.getRequestURI()
            System.out.println( "得到相对地址："+ request.getRequestURI());
            // String path=request.getServletContext().getRealPath("")+"uploaded";
//            String path=System.getProperty("user.dir")+"\\src\\main\\resources\\static\\upload\\";
            String path=System.getProperty("user.dir");
            path = path.substring(0, path.indexOf("b"));
            path = path + "webapps/upload/";
            String fileName = file.getOriginalFilename();
            fileName= IdWorkerUtil.getInstance().nextId()+fileName.substring(fileName.indexOf("."),fileName.length());
            String destFileName=path+fileName;
            System.out.println("path:"+path);

            File destFile = new File(destFileName);
            if(!destFile.exists()){
                destFile.getParentFile().mkdirs();
            }
            String url = "http://www.333blog.top"
                    + "/upload/"
                    + fileName;
            System.out.println("url:"+url);
            file.transferTo(destFile);
            json.put("success", 1);
            json.put("message", "上传成功");
            json.put("url", url);
        } catch (IllegalStateException | IOException e) {
            json.put("success", 0);
            json.put("message", "上传失败");
        }finally{
            wirte.print(json);
            wirte.flush();
            wirte.close();
        }
//        return json;
    }

}
